package com.voxel.sense.infomsg.module.firm.details;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ToastUtil;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.module.common.SlidingTabPageAdapter;
import com.voxel.sense.infomsg.module.firm.details.device.FirmDeviceFrag;
import com.voxel.sense.infomsg.module.firm.details.general.FirmGeneralInfoFrag;
import com.voxel.sense.infomsg.module.firm.details.institution.inCrease.IncreaseBranchActivity;
import com.voxel.sense.infomsg.module.firm.details.institution.list.InstitutionFrag;
import com.voxel.sense.infomsg.module.firm.details.video.FirmVideoFrag;
import com.voxel.sense.infomsg.module.map.MapActivity;
import com.voxel.sense.infomsg.utils.GPSUtils;
import com.voxel.sense.infomsg.utils.GlideUtils;
import com.voxel.sense.infomsg.view.NoScrollViewPager;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.CommonImagePagerActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.FirmListEntity;

/**
 * Created by chenyiyao on 2017/11/8.
 */

public class FirmInfoDetailActivity extends BViewActivity<FirmDetailContract.Presenter>
  implements FirmDetailContract.View<FirmListEntity> {
  @BindView(R.id.titlebar)
  TextTitleBar titlebar;
  @BindView(R.id.ctl_tip)
  SlidingTabLayout ctl_tip;
  @BindView(R.id.view_page)
  NoScrollViewPager view_page;
  @BindView(R.id.iv_phone)
  ImageView iv_phone;//电话
  @BindView(R.id.iv_pic)
  ImageView iv_pic;//公司图片
  @BindView(R.id.iv_level_icon)
  TextView iv_level_icon;//公司等级
  @BindView(R.id.iv_location)
  ImageView iv_location;//定位图标
  @BindView(R.id.iv_firm_type_icon)
  TextView iv_firm_type_icon;//公司性质
  @BindView(R.id.tv_name)
  TextView tv_name;//公司名
  @BindView(R.id.tv_details_area)
  TextView tv_details_area;//详细地址
  @BindView(R.id.tv_street)
  TextView tv_street;//街道
  @BindView(R.id.tv_detail_presenter)
  TextView tv_detail_presenter;//法人
  @BindView(R.id.tv_phone_numb)
  TextView tv_phone_numb;//电话号码
  @BindView(R.id.tv_over_numb)
  TextView tv_over_numb;
  @BindView(R.id.tv_ill_numb)
  TextView tv_ill_numb;
  @BindView(R.id.tv_fault_numb)
  TextView tv_fault_numb;

  private List<Fragment> mListdata;

  private FirmListEntity mCompanybean;
  private FirmListEntity.CompanyBaseinfoVoBean bean1;

  private String mFirmId;
  private double mLatitude = -1;
  private double mLongitude = -1;
//
  public static void show(Context context, String firmId) {
    show(context, null, firmId);
  }

  /**
   * 公司名字，或公司实体类，必须传一个
   *
   * @param context
   * @param bean    公司信息实体类
   * @param firmId  公司名
   */
  public static void show(Context context, FirmListEntity bean, String firmId) {
    Intent intent = new Intent(context, FirmInfoDetailActivity.class);
    if (bean != null) {
      Bundle bundle = new Bundle();
      bundle.putSerializable("bean", bean);
//      bundle.putSerializable("BaseinfoVoBean", bean1);
      intent.putExtras(bundle);
    }
    if (!TextUtils.isEmpty(firmId)) {
      intent.putExtra("firmId", firmId);
    }
    else {
      ToastUtil.showToastLong(Factory.app(), "界面跳转发生错误");
      return;
    }
    context.startActivity(intent);
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
  }

  @Override
  protected void onPause() {
    super.onPause();
    Jzvd.resetAllVideos();
  }

  @Override
  protected FirmDetailContract.Presenter initPresenter() {
    return new FirmDetailPresenter(this);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
  }

  @Override
  protected int getContentLayoutId() {
    return R.layout.activity_firm_info_detail;
  }

  @Override
  protected boolean initArgs(Bundle bundle) {
    if (bundle != null)
      mCompanybean = (FirmListEntity) bundle.getSerializable("bean");
    bean1 = (FirmListEntity.CompanyBaseinfoVoBean) bundle.getSerializable("BaseinfoVoBean");

    mFirmId = getIntent().getStringExtra("firmId");

    return super.initArgs(bundle);
  }

  @Override
  protected void initWidget() {
    super.initWidget();
    titlebar.setTitleText("污染源企业信息");
    view_page.setScroll(false);
    LoadFirmData(mCompanybean);
  }

  public void LoadFirmData(FirmListEntity entity) {
    if (entity == null)
      return;
    if (mCompanybean == null) {
      mCompanybean = entity;
    }
    FirmListEntity.CompanyBaseinfoVoBean baseInfo = entity.getCompanyBaseinfoVo();

    tv_details_area.setText(baseInfo.getDetailAddr());
    tv_name.setText("" + baseInfo.getCompanyName());
    if (!TextUtils.isEmpty(baseInfo.getStreet())) {
      tv_street.setText(baseInfo.getStreet());
      tv_street.setVisibility(View.VISIBLE);
      iv_location.setVisibility(View.VISIBLE);
    }
    else {
      tv_street.setVisibility(View.INVISIBLE);
      iv_location.setVisibility(View.INVISIBLE);
    }
    if (entity.getCompanyFileVo() != null && entity.getCompanyFileVo().size() > 0) {
      FirmListEntity.CompanyFileVoBean url = entity.getCompanyFileVo().get(0);
      GlideUtils.GlideLoadFirmPic(this, url.getFilePath(), R.mipmap.firm_logo_icon, iv_pic);
    }
    else {
      GlideUtils.GlideLoadPicNoDefault(this, R.mipmap.firm_logo_icon, iv_pic);
    }

    //管理等级
    if (!TextUtils.isEmpty(baseInfo.getRegulationLevel())) {
      iv_level_icon.setVisibility(View.VISIBLE);
//      GlideUtils.GlideLoadConfigPNGIcon(this, baseInfo.getRegulationLevel(), iv_level_icon);
      iv_level_icon.setText(baseInfo.getRegulationLevel());
    }
    else {
      iv_level_icon.setVisibility(View.INVISIBLE);
    }
    //监管性质
    if (!TextUtils.isEmpty(baseInfo.getRegulationType())) {
//      GlideUtils.GlideLoadConfigPNGIcon(this,
//        baseInfo.getRegulationType(), iv_firm_type_icon);
      iv_firm_type_icon.setText(baseInfo.getRegulationType());
      iv_firm_type_icon.setVisibility(View.VISIBLE);
    }
    else {
      iv_firm_type_icon.setVisibility(View.INVISIBLE);
    }

    //没有电机则隐藏图片
    String phone = baseInfo.getPhone();
    if (TextUtils.isEmpty(phone)) {
      iv_phone.setVisibility(View.INVISIBLE);
    }
    else {
      iv_phone.setVisibility(View.VISIBLE);

    }

    tv_phone_numb.setText(baseInfo.getPhone());
    tv_detail_presenter.setText(baseInfo.getLegalRepresent());
    tv_over_numb.setText(mCompanybean.getAbnormalCount());
    tv_ill_numb.setText(mCompanybean.getCompanyBaseinfoVo().getBadDescription());
    tv_fault_numb.setText(mCompanybean.getCompanyBaseinfoVo().getEquipmentfailure());
    //转换坐标
    String longitude = mCompanybean.getCompanyBaseinfoVo().getLongitude();
    String latitude = mCompanybean.getCompanyBaseinfoVo().getLatitude();
    try {
      double v1 = Double.parseDouble(latitude);
      double v2 = Double.parseDouble(longitude);
      double[] doubles = GPSUtils.bd09_To_Gcj02(v1, v2);
      mLatitude = doubles[0];
      mLongitude = doubles[1];
    }
    catch (NumberFormatException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void initData() {
    super.initData();

    if (mCompanybean == null && !TextUtils.isEmpty(mFirmId)) {

      mPresenter.doLoadData(mFirmId);
      showProgressDialog("");
    }

    mListdata = new ArrayList<>();
    //初始化fragment并将公司名字传入其中
    Bundle bundle = new Bundle();
    bundle.putString(IntentConstants.STRING_TYPE, mFirmId);
    InstitutionFrag resourceChartDataFragment = new InstitutionFrag();//实时数据
    FirmGeneralInfoFrag firmGeneralInfoFrag = new FirmGeneralInfoFrag();//公司表格信息
    FirmVideoFrag firmVideoFragment = new FirmVideoFrag();//视频
    FirmDeviceFrag firmDeviceFragment = new FirmDeviceFrag();//设备

    resourceChartDataFragment.setArguments(bundle);
    firmGeneralInfoFrag.setArguments(bundle);
    firmVideoFragment.setArguments(bundle);
    firmDeviceFragment.setArguments(bundle);
    //将fragment的添加入管理集合中
    mListdata.add(Fragment.instantiate(this, InstitutionFrag.class.getName(), bundle));
    mListdata.add(Fragment.instantiate(this, FirmGeneralInfoFrag.class.getName(), bundle));
    mListdata.add(Fragment.instantiate(this, FirmVideoFrag.class.getName(), bundle));
    mListdata.add(Fragment.instantiate(this, FirmDeviceFrag.class.getName(), bundle));

    //page适配器
    String[] mTitle = {"站位信息", "综合信息", "实时视频", "设备管理"};
    FragmentPagerAdapter pagerAdapter = new SlidingTabPageAdapter(getSupportFragmentManager(), mListdata, mTitle);
    view_page.setOffscreenPageLimit(2);
    view_page.setAdapter(pagerAdapter);
    ctl_tip.setViewPager(view_page);
    ctl_tip.setOnTabSelectListener(new OnTabSelectListener() {
      @Override
      public void onTabSelect(int position) {
        L.d("onTabSelect" + position);
        //切换界面，停止播放
        if (position != 2) {
          Jzvd.resetAllVideos();
        }
      }

      @Override
      public void onTabReselect(int position) {
        L.d("onTabReselect" + position);
      }
    });
  }

  @Override
  protected void initEven() {
    super.initEven();

    //TODO:未开发完成暂时隐藏添加项目模块
//        titlebar.setRightTextAndLis("+站位", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IncreaseBranchActivity.show(FirmInfoDetailActivity.this, mCompanybean.getCompanyBaseinfoVo().getCompanyName(), mLatitude, mLongitude);
//            }
//        });
  }

  @OnClick({R.id.iv_phone, R.id.tv_street, R.id.iv_location, R.id.iv_pic, R.id.cl_areal_content})
  void onClic(View v) {
    switch (v.getId()) {
      case R.id.iv_location://跳转地图定位
      case R.id.tv_street://跳转地图定位
      case R.id.cl_areal_content://跳转地图定位
        if (mCompanybean == null) {
          return;
        }

        String longitude = mCompanybean.getCompanyBaseinfoVo().getLongitude();
        String latitude = mCompanybean.getCompanyBaseinfoVo().getLatitude();

        if (mLatitude == -1 || mLongitude == -1) {
          ToastUtil.showToastLong(Factory.app(), "暂时无该公司的坐标");
          return;
        }
        else {
          MapActivity.show(this, tv_details_area.getText().toString(), mLatitude, mLongitude);
        }
        break;
      case R.id.iv_phone:
        if (mCompanybean == null)
          return;
        //跳转拨号界面
        String phone = mCompanybean.getCompanyBaseinfoVo().getPhone();
        if (!TextUtils.isEmpty(phone)) {
          startActivity(IntentUtils.getDialIntent(phone));
        }
        else {
        }
        break;
      case R.id.iv_pic:

        if (mCompanybean == null)
          return;

        ArrayList list = new ArrayList<>();
        List<FirmListEntity.CompanyFileVoBean> companyFileVo = mCompanybean.getCompanyFileVo();
        //判断是否有公司照片，没有则显示的是默认图
        if (companyFileVo != null && companyFileVo.size() > 0
          && !TextUtils.isEmpty(companyFileVo.get(0).getFilePath())) {
          list.add(CommonConstants.FILE_FIRM_URL + companyFileVo.get(0).getFilePath());
        }
        else {

          list.add(R.mipmap.firm_logo_icon);
        }
//        CommonImagePagerActivity.showImages(this, list, 0);
        break;
    }
  }

  @Override
  public void onBackPressed() {
    if (Jzvd.backPress()) {
      return;
    }
    super.onBackPressed();
  }

  @Subscribe
  public void onEvent(EventEntity event) {

  }

  @Override
  public void refreshBaseInfo(FirmListEntity entity) {
    LoadFirmData(entity);
  }

  @Override
  public void onRefreshData() {

  }

  @Override
  public void onFailureUI() {

  }
}
